//
//  YZDieoutSearchResultController.m
//  VET
//
//  Created by 刘文靖 on 2018/8/2.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZDieoutSearchResultController.h"
#import "MJRefresh.h"
#import "YZDieOutCell.h"
#import "YZDieOutModel.h"
#import "MJExtension.h"
#import "YZSearchBar.h"
#import "YZPigDeathDetailVC.h"
#import "YZPigGroupDeathDetailVC.h"
#import "YZActionSheet.h"
#import "YZDieOutTrackVC.h"
#import "YZPopupController.h"
#import "YZPopupCustomView.h"
#import "YZWorkbenchAPI.h"
#import "YZRouter+AutoVC.h"
@interface YZDieoutSearchResultController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,YZDieOutCellDelegate,YZActionSheetDelegate>
@property (strong, nonatomic) NSMutableArray<YZDieOutModel *> *dataSource;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) YZDieOutModel *selectedModel;
@property (strong, nonatomic) NSString *batchNo;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (assign, nonatomic) NSInteger currentPage;
@property (nonatomic, strong) YZSearchBar *searchBar;
@property (strong, nonatomic) NSIndexPath *selectedIndexPath;
@end
#define kPagePerCount 10
@implementation YZDieoutSearchResultController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColorWithHex(0xffffff);
    [self setupMainView];
    [self setupRefresh];
}

- (void)setupMainView{
    self.cancelBtn = [[UIButton alloc] init];
    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelBtn setTitleColor:kColorWithHex(0x434343) forState:UIControlStateNormal];
    self.cancelBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
    [self.view addSubview:self.cancelBtn];
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(36, 18));
        make.left.offset(18);
        make.top.offset(11 + kStatusBarHeight);
    }];
    [self.view addSubview:self.searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kScreenWidth - 80, 36));
        make.left.mas_equalTo(self.cancelBtn.mas_right).offset(0);
        make.top.offset(kStatusBarHeight);
    }];
    @weakify(self)
    [[self.cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)setupRefresh {
    
    // 设置刷新控件
    @weakify(self)
    
    // header
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadNewData];
    }];
    self.tableView.mj_header = header;
    
    // footer
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        [self loadMoreData];
    }];
    self.tableView.mj_footer = footer;
    self.tableView.mj_footer.hidden = YES;
}

- (void)loadNewData{
    if (self.batchNo.length == 0) {
        [self.tableView.mj_header endRefreshing];
        return;
    }
    @weakify(self)
    [[YZDieOutModelAPI requestDieoutList:0 number:self.batchNo] subscribeNext:^(NSDictionary *dict) {
        @strongify(self)
        self.currentPage = 1;
        self.dataSource = [YZDieOutModel mj_objectArrayWithKeyValuesArray:dict[@"list"]];
        if (self.dataSource.count < kPagePerCount) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData{
    //[self.tableView.mj_footer endRefreshing];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.rowHeight = 163;
        [_tableView registerClass:[YZDieOutCell class] forCellReuseIdentifier:@"YZDieOutCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.top.offset(64);
        }];
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    return _tableView;
}

#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZDieOutCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YZDieOutCell"];
    cell.model = self.dataSource[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YZDieOutModel *model = self.dataSource[indexPath.row];
    if ([model.type isEqualToString:@"swine"]) {
        YZPigDeathDetailVC *pigDeathDetailVC = [YZPigDeathDetailVC new];
        pigDeathDetailVC.model = model;
        [[YZRouter sharedInstance] pushVC:pigDeathDetailVC];
    }else
    {
        YZPigGroupDeathDetailVC *pigGroupDeathDetailVC = [YZPigGroupDeathDetailVC new];
        pigGroupDeathDetailVC.model = model;
        [[YZRouter sharedInstance] pushVC:pigGroupDeathDetailVC];
    }
}

#pragma mark - YZSwineArchieveCellDelegate
- (void)cellDidClickManage:(YZDieOutCell *)cell{
    YZActionSheet *sheet = [[YZActionSheet alloc] initWithTitle:nil sheetTitles:@[@"死淘跟踪",@"删除"] cancleBtnTitle:@"取消" sheetStyle:YZActionSheetDefault delegate:self];
    sheet.sheetHeight = 55;
    sheet.subtitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.subtitleColor = kColorWithHex(0x393939);
    sheet.lineColor = kColorWithHex(0xD9D9D9);
    sheet.cancleHeight = 55;
    sheet.bottomMarginHeight = 15;
    sheet.cancelTitleFont = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    sheet.cancelTitleColor = kColorWithHex(0x393939);
    self.selectedModel = cell.model;
    self.selectedIndexPath = [self.tableView indexPathForCell:cell];
    [sheet show];
}

#pragma mark - YZActionSheetDelegate
/**
 点击actionSheet代理方法
 
 @param actionSheet actionSheet
 @param buttonIndex index
 */
- (void)actionSheet:(YZActionSheet *)actionSheet clickButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://死淘跟踪
        {
            YZDieOutTrackVC *trackVC = [[YZDieOutTrackVC alloc] init];
            trackVC.trackId = self.selectedModel.dieOutId;
            [[YZRouter sharedInstance] pushVC:trackVC];
        }
            ;
            break;
            
        case 1://删除
        {
            YZPopupConfrimCustomView *customView = [[YZPopupConfrimCustomView alloc] init];
            @weakify(self)
            [customView setupUIWithTitle:nil message:@"确定删除当前死淘记录？删除后不可恢复已记录信息。" confirmTitle:@"删除" cancelTitle:@"取消" confirmHandler:^{
                @strongify(self)
                // 删除猪只
                NSString *dieOutId = [@(self.selectedModel.dieOutId) stringValue];
                @weakify(self)
                [[YZWorkbenchAPI deleteDeadSignAPIWithParams:dieOutId] subscribeNext:^(id  _Nullable x) {
                    @strongify(self)
                    [[NSNotificationCenter defaultCenter] postNotificationName:kDieoutRefreshNotification object:nil];
                    [self.YZ_popupController dismiss];
                    [self.dataSource removeObject:self.selectedModel];
                    [self.tableView deleteRowsAtIndexPaths:@[self.selectedIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
                } error:^(NSError * _Nullable error) {
                    @strongify(self)
                    [self.YZ_popupController dismiss];
                }];
                
            } cancelHandler:^{
                @strongify(self)
                [self.YZ_popupController dismiss];
            }];
            [self.YZ_popupController presentContentView:customView];
        }
            break;
    }
}
- (void)actionSheetCancle:(YZActionSheet *)actionSheet{}

#pragma mark - getter && setter
-(YZSearchBar *)searchBar{
    if (!_searchBar){
        _searchBar = [[YZSearchBar alloc] init];
        _searchBar.backgroundColor = [UIColor clearColor];
        _searchBar.delegate = self;
        //光标颜色
        _searchBar.cursorColor = kColorWithHex(0x32BE60);
        //TextField
        _searchBar.searchBarTextField.backgroundColor = kColorWithHex(0xFAFAFA);
        _searchBar.searchBarTextField.layer.cornerRadius = 10;
        _searchBar.searchBarTextField.layer.masksToBounds = YES;
        _searchBar.searchBarTextField.layer.borderColor = kColorWithHex(0xFAFAFA).CGColor;
        _searchBar.searchBarTextField.layer.borderWidth = 1.0;
        _searchBar.searchBarTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
        _searchBar.searchBarTextField.placeholder = @"搜索";
        _searchBar.delegate = self;
        //去掉取消按钮灰色背景
        _searchBar.hideSearchBarBackgroundImage = YES;
        [_searchBar.searchBarTextField becomeFirstResponder];
    }
    return _searchBar;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.view endEditing:YES];
    self.batchNo = searchBar.text;
    // 请求数据
    [self.tableView.mj_header beginRefreshing];
}
@end
